layui.define(['element', 'api', 'amis', 'schema', 'listener', 'api', 'jqgrid', 'open_domain',
    'gs_domain_design','gs_domain_basic_design',
    'domain_design','workflow_design', 'domain_design_vo', 'brms_design', 'edropdown', 'form', 'resource_content', 'ztree', 'resource_properties','fast_config', 'utils', 'schema_render', 'resource_tabs'
], function(exports) {
    "use strict";



    function getMetaPath(value){
        var path;
        if(contextmenuData.data.path===null || contextmenuData.data.path===''){
            path = value;
        }else{
            path = contextmenuData.data.path + "#/" + value;
        }
        return path;
    }

    /**
     * 创建文件
     * @param path
     */
    function createMetaData(metaType, path){
        function send(path){
            api.post({
                enableRootPath: true,
                url: "schemas/" + metaType + "/fields",
                data: {path:path},
                async: false,
                success: function(data){
                    selectedNode({
                        id: path
                    })
                }
            });
        }


        layer.prompt({
            formType: 0,
            value: '',
            title: '请输入文件名称',
            area: ['200px', '20px'] //自定义文本域宽高
        }, function(value, index, elem){
            var path = getMetaPath("fields/" + value);
            send(path);
            layer.close(index);
        });
    }

    /**
     * 启用
     * @param path
     */
    function enable(metaType, path){
        function send(){
            api.put({
                enableRootPath: true,
                url: "schemas/" + metaType + "/enable",
                data: {path:path},
                async: false,
                success: function(data){
                    selectedNode({
                        id: path
                    })
                }
            });
        }


        layer.confirm('是否确认该操作？', {
            btn: ['确认', '取消']
        }, function(index, layero){
            send();
            layer.close(index);
        }, function(index){
            layer.close(index);
        });
    }

    /**
     * 启用
     * @param path
     */
    function disable(metaType, path){
        function send(){
            api.put({
                enableRootPath: true,
                url: "schemas/" + metaType + "/disable",
                data: {path:path},
                async: false,
                success: function(data){
                    selectedNode({
                        id: path
                    })
                }
            });
        }


        layer.confirm('是否确认该操作？', {
            btn: ['确认', '取消']
        }, function(index, layero){
            send();
            layer.close(index);
        }, function(index){
            layer.close(index);
        });

    }

    /**
     * 重命名
     * @param path
     */
    function rename(name, path){
        function send(name){
            api.put({
                enableRootPath: true,
                url: "resource/rename/" + name,
                data: {path:path},
                async: false,
                success: function(data){
                    selectedNode({
                        id: data
                    })
                }
            });
        }



        layer.prompt({
            formType: 0,
            value: name,
            title: '请输入文件名称',
            area: ['200px', '20px'] //自定义文本域宽高
        }, function(value, index, elem){
            send(value);
            layer.close(index);
        });
    }



    /**
     * 创建文件
     * @param path
     */
    function createFile(metaType){
        function send(path){
            api.post({
                enableRootPath: true,
                type: "POST",
                url: "schemas/" + metaType,
                data: {path:path},
                async: false,
                success: function(data){
                    selectedNode({
                        id: path+".json"
                    })
                    // reloadResource()
                }
            });
        }


        layer.prompt({
            formType: 0,
            value: '',
            title: '请输入文件名称',
            area: ['200px', '20px'] //自定义文本域宽高
        }, function(value, index, elem){
            var path = getFilePath(value);
            send(path);
            layer.close(index);
        });
    }


    /**
     * 获取右键选择数据 -> 文件路径
     */
    function getContextmenuFilePath(){
        return contextmenuData.data.path;
    }

    /**
     * 删除
     * @param path
     */
    function deleteResource(){
        //获取
        var path = getContextmenuFilePath();
        api.delete({
            enableRootPath: true,
            url: "resource",
            data: {path:path},
            async: false,
            success: function(data){
                selectedNode({
                    id: path
                })
            }
        });
    }

    function getParentPath(path) {
        var slashIndex = path.lastIndexOf("/");
        if(slashIndex != -1){
            path = path.substring(0, slashIndex);

            if(path.lastIndexOf('#') == path.length-1){
                return path.substring(0, path.lastIndexOf('#'));
            }else{
                return path
            }

        }else{
            return path
        }
    }

    function openDoamin(data, target) {
        var treeNode = data;
        var id = target.id;

        open_domain.render({
            elem: utils.getTabElem(id),
            treeNode: treeNode,
            viewMode:viewMode,
            pearBody : pearBody,
            amisData: utils.getGlobalEnv(treeNode.data),
            resource_tabs : resource_tabs_obj
        })
    }

    function designDoamin(data, target) {
        var treeNode = data;
        var id = target.id;

        domain_design.render({
            elem: utils.getTabElem(id),
            data:data,
            treeNode: treeNode,
            viewMode: viewMode,
            pearBody : pearBody,
            amisData: utils.getGlobalEnv(treeNode.data),
            callback: {
                reloadtree: function reloadCallback(data){
                    // reloadResource();
                    selectedNode(data);
                }
            }
        })
    }

    function designVo(data, target) {
        var treeNode = contextmenuData;
        var id = target.id;

        domain_design_vo.render({
            elem: utils.getTabElem(id),
            data:data,
            treeNode: treeNode,
            viewMode: viewMode,
            pearBody : pearBody,
            amisData: utils.getGlobalEnv(treeNode.data),
            callback: {
                reloadtree: function reloadCallback(data){
                    selectedNode(data);
                }
            }
        })
    }



    function getFilePath(value){
        var path;
        if(contextmenuData.data.path===null || contextmenuData.data.path===''){
            path = value;
        }else{
            path = contextmenuData.data.path + "/" + value;
        }
        return path;
    }

    function reloadResource(){
        
        treeObj.refresh();
        //加载树
        treeconf(utils.contextData.trees_settings[utils.contextData.currentTreeId]);
    }

    function refreshTabContentData(tree){
        // var tree = getTree();
        let currentTreeId = utils.contextData.currentTreeId;
        $.each(resource_tabs_obj.option.tabIdContentFn, function(index, item){
            if(index.indexOf(currentTreeId)>-1){
                var oldTreeNode = item.data.option.treeNode;
                var selectNode = selectedPath(tree, oldTreeNode.id);
                if(selectNode) {
                    item.data.option.treeNode = selectNode;
                }else{
                    delete resource_tabs_obj.option.tabIdContentFn["#treenode_" + item.data.option.elem];
                }
            }
        })
    }

    function closeTabAndOpenNew(id, tabId){
        var resouceId = "#treenode_" + tabId;
        pearBody.delTabByElem('content', tabId);
        delete resource_tabs_obj.option.tabIdContentFn[resouceId];
        selectedNode({id: id})
        
        debugger;
    }


    function selectedNode(data){
        // debugger
        //1、刷新树，渲染追加新增的节点
        reloadResource();
        //    2、根据参数获取树节点
        var tree = getTree();


        refreshTabContentData(tree);

        if(data && data.id){
            let node = selectedPath(tree, data.id);
            // let node = tree.getNodeByParam("id", data.id, null);
            //3、选择目标节点
            if(node !== null){
                tree.selectNode(node);
                //单击事件
                tree.setting.callback.onClick(event,getTreeId(),node);
            }
        }
        
            // const treeNode = JSON.parse(sessionStorage.getItem('content-pear-current-treeNode'))
            // if(!!treeNode && treeNode !== null){
            //         // 再次激活当前tab页面的树id
            //     var id = treeNode.id
                
            //     let node = selectedPath(tree, id);
            //     //3、选择目标节点
            //     tree.selectNode(node);
            //     //单击事件
            //     tree.setting.callback.onClick(event,getTreeId(),node);
            // }

    }


    function getTreeId(){
        return treeObj.option.elem.slice(1);
    }

    function getTree(){
        //    2、根据参数获取树节点
        var tree = $.fn.zTree.getZTreeObj(getTreeId());
        return tree;
    }

    

    function selectedPath(tree, path) {
        let node = tree.getNodeByParam("id", path, null);
        if(node == null && path.indexOf("/") != -1){
            node = selectedPath(tree, getParentPath(path))
        }

        return node;
    }

    /**
     * 创建目录
     * @param path
     */
    function createFolder(){

        function send(path){
            api.post({
                enableRootPath: true,
                type: "POST",
                url: "resource/folder",
                data: {path:path},
                async: false,
                success: function(data){
                    selectedNode({
                        id: path
                    })
                }
            });
        }


        layer.prompt({
            formType: 0,
            value: '',
            title: '请输入文件夹名称',
            area: ['200px', '20px'] //自定义文本域宽高
        }, function(value, index, elem){
            var path = getFilePath(value);
            send(path);
            layer.close(index);
        });
    }

    function resetContent(contentElem){
        $(contentElem).remove();
        $('.layui-body.gs-body').append('<div id="'+contentElem.slice(1)+'"></div>')
    }



    function createFileListener(data) {

        createFile('domain_model')
    }

    function createDomainFieldListener(data) {

        createMetaData('domain_model', contextmenuData.data.path)
    }

    function renameListener(data) {
        rename(contextmenuData.data.name, contextmenuData.data.path)
    }

    function enableListener(data) {
        enable(contextmenuData.data.name, contextmenuData.data.path)
    }

    function disableListener(data) {
        disable(contextmenuData.data.name, contextmenuData.data.path)
    }

    function openDomainListener(data, target) {
        openDoamin(data, target)
    }

    function designDomainListener(data, target) {
        designDoamin(data, target)
    }

    function designVoListener(data, target){
        designVo(data, target)
    }


    function createFolderListener(data) {
        createFolder()
    }

    function removeListener(data) {
        deleteResource();
    }

    function createDomainModelListener(data) {
        createMetaData();
    }

    /**
     * Button component
     * */
    var MOD_NAME = 'resource_tree',
        $ = layui.jquery,
        contextmenuData,
        contentElem,
        elem,
        open_domain = layui.open_domain,
        domain_design = layui.domain_design,
        domain_design_vo = layui.domain_design_vo,
        brms_design = layui.brms_design,
        edropdown = layui.edropdown,
        form = layui.form,
        laytpl = layui.laytpl,
        resource_content = layui.resource_content,
        resource_properties = layui.resource_properties,
        ztree = layui.ztree,
        api = layui.api,
        schema = layui.schema,

        workflow_design = layui.workflow_design,

        pearBody,
        resource_tabs_obj,
        amis = layui.amis,
        schema_render = layui.schema_render,
        resource_tabs = layui.resource_tabs,
        treeApi,
        treeObj,
        resource_tree_obj,
        viewMode,
        schemaType,
        listener = layui.listener,
        utils = layui.utils,
        // fast_config = layui.fast_config,
        treeClickListener,

        //监听器
        contextMenuListeners = {
            createFileListener:createFileListener,
            removeListener:removeListener,
            createDomainModelListener:createDomainModelListener,
            createDomainFieldListener:createDomainFieldListener,
            renameListener:renameListener,
            enableListener:enableListener,
            disableListener:disableListener,
            openDomainListener:openDomainListener,
            designDomainListener:designDomainListener,
            createFolderListener:createFolderListener
        },
        contentPanelListeners = {
            designDomainListener:designDomainListener,
            designVoListener:designVoListener,
            openDomainListener:openDomainListener,
        }

    ;



    function zTreeOnRightClick(event, treeId, treeNode) {

        utils.setTreeNodeData(treeNode.data);
        let treeobj = $.fn.zTree.getZTreeObj(treeId)
        schemaType = treeobj.setting.view.schemaType;
        // 将右击事件的节点数据绑定到以下变量中
        contextmenuData = treeNode;
        utils.contextData.contextmenuData = contextmenuData;
        utils.contextData.currentTreeId = treeId;
    };

    var resource_tree = function(opt) {
        this.option = opt;
    };


    function getContextmenuData(){
        return contextmenuData;
    }


    function registerListeners(){
        $.each(contextMenuListeners, function(name ,_listener){
            listener.registerContextMenuListener(name, _listener)
        })
        $.each(contentPanelListeners, function(name ,_listener){
            listener.registerContentPanelListener(name, _listener)
        })

        listener.registerResourceTreeClickListener('extention_resourceTreeClickListener', extention_resourceTreeClickListener);

    }


    /**
     * 扩展_单击树监听器
     * @param {} event
     * @param {*} treeId
     * @param {*} treeNode
     */
    function extention_resourceTreeClickListener(event, treeId, treeNode, option, pearBody, resource_tabs_obj){
        var onClickListener = option.onClickListener;

        if(onClickListener && typeof onClickListener === 'function'){
            onClickListener(event, treeId, treeNode);
        }
    }

    /**
     * Button start loading
     * 加载树
     * */
    function treeconf(option){

        registerListeners();
        var settings = {
            view: {
                onKeyboard: true,
                showLine: false,
                theme:'default',
                treeMode: option.treeMode,
                keepActiveParentNode:'.box1'
            },
            check: {
                enable: true
            },
            data: {
                simpleData: {
                    enable: true
                }
            }
            ,callback:{
                onLeafEnter: function(treeId,treeNode){
                    console.log(treeId,treeNode)
                },
                onClick: function zTreeOnClick(event, treeId, treeNode) {
                    utils.contextData.currentTreeId = treeId;
                    utils.setTreeNodeData(treeNode.data);

                    var treeObj = $.fn.zTree.getZTreeObj(treeId)
                    var schemaType = treeObj.setting.view.schemaType;

                    contextmenuData = treeNode;

                    var metaType = treeNode.data.type.metaType;
                    var resourceTypeSchema = schema.get(schemaType);
                    var typeSchema = resourceTypeSchema[metaType];
                    if(typeSchema.contentPanel){
                        sessionStorage.setItem('content-schemaType',JSON.stringify(schemaType))
                    }

                    var onClickListener = option.onClickListener;
                    if(onClickListener && typeof onClickListener === 'function'){
                        // if(treeClickListener && typeof treeClickListener === 'function'){
                            // console.log(onClickListener,'onClickListener')
                        onClickListener(event, treeId, treeNode);
                    }
                    var listeners = listener.getResourceTreeClickListeners()
                    // console.log(listeners,'listeners')
                    $.each(listeners, function(index, listener){
                        // console.log(listener,'listener')
                        listener(event, treeId, treeNode, option, pearBody, resource_tabs_obj);
                    })
                    
                    
                },
                onRightClick: zTreeOnRightClick
            }
        };

        settings.view.schemaType =  option.schemaType

        treeObj = ztree.render({
            elem: option.elem,
            setting: settings,
            enableRootPath:option.enableRootPath,
            api: option.api
        });

        edropdown.render({
            elem: option.elem //在 id="demo" 的元素中触发事件。也可以直接设置为 document，从而重置整个右键菜单
            ,trigger: 'contextmenu' //右键事件
            ,click: function(obj, f, e){
                // var data = contextmenuData.data;

                schema_render.render({
                    elem: obj.id,
                    schema: obj,
                    contextData: contextmenuData,
                    callback: {
                        dialog: function dialogCallback(data){
                            // reloadResource();
                            selectedNode(data);
                        }
                    }
                })

            },
            beforeRander: function(config){
                var data = getContextmenuData();
                var resourceTypeSchema = schema.get(schemaType);
                if(resourceTypeSchema){
                    var resourceSchema = resourceTypeSchema[data.data.type.metaType];
                    if(resourceSchema && resourceSchema.funcs){
                        var enabled = data.data.enabled;
                        config = $.grep(resourceSchema.funcs,
                            function(obj, i) {
                                if(obj.disabledOn){
                                    return utils.evalExpression(obj.disabledOn, utils.getGlobalEnv(getContextmenuData().data))
                                }
                                if(enabled && obj['id'] === 'enable'){
                                    return false;
                                }else if(!enabled && obj['id'] === 'disable'){
                                    return false;
                                }
                                return true;
                            });
                        config.resourceSchema = resourceSchema;
                    }

                }
                return config;
            },
            data: []
        });

    }


    resource_tree.prototype.selectedNode = function(data) {
        selectedNode(data);
    }

    resource_tree.prototype.closeTabAndOpenNew = function(id, tabId) {
        closeTabAndOpenNew(id, tabId);
    }

    resource_tree.prototype.render = function(opt) {

        var option = {
            elem: opt.elem,
            contentElem: opt.contentElem,
            enableRootPath:opt.enableRootPath,
            api:opt.api,
            treeMode: opt.treeMode,
            viewMode: opt.viewMode,
            schemaType:opt.schemaType,
            onClickListener: opt.onClickListener
        }

        // treeClickListener = option.onClickListener;

        viewMode = option.viewMode;
        contentElem = option.contentElem;
        elem = option.elem;
        schemaType = option.schemaType;

        treeconf(option);

        //因刷新树时会清空你tab，所以该方法单独抽出。
        resource_tabs_obj = resource_tabs.render({
            elem: 'content',
            viewMode: option.viewMode
        });

        pearBody = resource_tabs_obj.option.pearBody;

        resource_tree_obj = new resource_tree(option);
        return resource_tree_obj
    }


    exports(MOD_NAME, new resource_tree());
});
